<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <!-- 引入 bootstrap 样式表 -->
    <link rel="stylesheet" href="./css/bootstrap.min.css" />
    <style>
      body {
        padding-top: 50px;
      }
    </style>
  </head>

  <body>
    <!-- 栅格系统 -->
    <div class="container">
      <div class="d-flex justify-content-between align-items-center">
        <h1>图书管理</h1>
        <button
          class="btn btn-success btn-sm"
          data-bs-toggle="modal"
          data-bs-target="#addModal"
        >
          添加
        </button>
      </div>
      <table
        class="table table-bordered table-striped table-dark table-hover text-center"
      >
        <thead>
          <!-- 表头行 -->
          <tr>
            <th scope="col">Id</th>
            <th scope="col">书名</th>
            <th scope="col">作者</th>
            <th scope="col">出版社</th>
            <th scope="col">操作</th>
          </tr>
        </thead>
        <tbody>
          <!-- 表格中的每一行 -->
          <tr>
            <th scope="row">xxx</th>
            <td>xxx</td>
            <td>xxx</td>
            <td>xxx</td>
            <td>
              <button type="button" class="btn btn-link btn-sm btn-delete">
                删除
              </button>
              <button type="button" class="btn btn-link btn-sm btn-update">
                编辑
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <!-- add Modal -->
    <div class="modal fade" id="addModal">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">添加图书</h5>
            <button
              type="button"
              class="btn-close"
              data-bs-dismiss="modal"
              aria-label="Close"
            ></button>
          </div>
          <div class="modal-body">
            <form id="addForm" class="p-3">
              <!-- 书名 -->
              <div class="mb-3">
                <label class="form-label">书名</label>
                <input
                  type="text"
                  name="bookname"
                  class="form-control"
                  placeholder="请输入图书名称"
                  name="bookname"
                />
              </div>
              <!-- 作者 -->
              <div class="mb-3">
                <label class="form-label">作者</label>
                <input
                  type="text"
                  name="author"
                  class="form-control"
                  placeholder="请输入作者名字"
                  name="author"
                />
              </div>
              <!-- 出版社 -->
              <div class="mb-3">
                <label class="form-label">出版社</label>
                <input
                  type="text"
                  name="publisher"
                  class="form-control"
                  placeholder="请输入出版社名称"
                  name="publisher"
                />
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-secondary"
              data-bs-dismiss="modal"
            >
              取消
            </button>
            <button type="button" class="btn btn-primary" id="addBtn">
              确认
            </button>
          </div>
        </div>
      </div>
    </div>
    <!-- add Modal -->
    <div class="modal fade" id="editModal">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">编辑图书</h5>
            <button
              type="button"
              class="btn-close"
              data-bs-dismiss="modal"
              aria-label="Close"
            ></button>
          </div>
          <div class="modal-body">
            <form id="editForm" class="p-3">
              <input type="hidden" name="id" />
              <!-- 书名 -->
              <div class="mb-3">
                <label class="form-label">书名</label>
                <input
                  type="text"
                  name="bookname"
                  class="form-control"
                  placeholder="请输入图书名称"
                  name="bookname"
                />
              </div>
              <!-- 作者 -->
              <div class="mb-3">
                <label class="form-label">作者</label>
                <input
                  type="text"
                  name="author"
                  class="form-control"
                  placeholder="请输入作者名字"
                  name="author"
                />
              </div>
              <!-- 出版社 -->
              <div class="mb-3">
                <label class="form-label">出版社</label>
                <input
                  type="text"
                  name="publisher"
                  class="form-control"
                  placeholder="请输入出版社名称"
                  name="publisher"
                />
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-secondary"
              data-bs-dismiss="modal"
            >
              取消
            </button>
            <button type="button" class="btn btn-primary" id="editBtn">
              确认
            </button>
          </div>
        </div>
      </div>
    </div>
    <!-- 引入 lib 目录下的 bootstrap 和 axios -->
    <script src="./lib/axios.js"></script>
    <!-- 快速获取表单数据  key=value {key:value}  -->
    <script src="./lib/form-serialize.js"></script>
    <!-- bootstrap的js -->
    <script src="./lib/bootstrap.min.js"></script>
    <script>
       // 1. 配置基地址 
       axios.defaults.baseURL = 'http://ajax-api.itheima.net'
      //  /api/books

      // 2. 当所有资源加载完毕的时候，请求数据，渲染列表
      window.addEventListener('load', function(){
        getBooks()
      })

      // 3. 封装获取全部书籍的方法
      const tbody = document.querySelector('tbody')
      function getBooks(){
        axios({
          url:'/api/books',
          // method:'get', // get是默认值，可以省略
        }).then(res => {
          console.log(res)
          const htmlArr = res.data.data.map(el => {
            
            const {id, bookname, createdAt, author, publisher, updatedAt} = el 
            return `
                <tr>
                <th scope="row">${id}</th>
                <td>${bookname}</td>
                <td>${author}</td>
                <td>${publisher}</td>
                <td>
                  <button type="button"  data-id=${id} class="btn btn-link  btn-sm btn-delete">
                    删除
                  </button>
                  <button type="button" data-id=${id} class="btn btn-link btn-sm btn-update">
                    编辑
                  </button>
                </td>
              </tr>
            `
          }) // end map 


          tbody.innerHTML = htmlArr.join('')
        })
      }


      // 1. 添加图书 
      // 让这个弹窗可以手动开启或者关闭
      const addModal = new bootstrap.Modal('#addModal')
      //  new bootstrap.Modal ==> js方式调用开启或者关闭弹窗
      const addForm = document.querySelector('#addForm')
      const addBtn = document.querySelector('#addBtn')

      // 点击确认的时候，将输入的内容发送给后端存起来
      addBtn.addEventListener('click', function(){
          // 使用serialize ==> 快速获取表单元素的值
          const data = serialize(addForm, {hash:true})
          // console.log('data' , data)
          axios({
            url:'/api/books',
            method:'POST',
            data
          }).then(res => {
            // 如果请求成功了，应该把弹窗关掉，还要渲染更新数据
            getBooks()
            // 关掉弹窗
            addModal.hide()
            // 重置表单
            addForm.reset()
          })
      })

      // 删除功能
      tbody.addEventListener('click', function(e){
        // 看某个元素是否包含某个类名
        if (e.target.classList.contains('btn-delete')){
          const id = e.target.dataset.id
          axios({
            url:`/api/books/${id}`,
            method:'DELETE'
          }).then(res => {
            console.log(res)
            alert('删除成功')
            getBooks()
          })
          
        } // end if 
      })


      // ==> 编辑图书
      const editModel = new bootstrap.Modal('#editModal')
      const editForm = document.querySelector('#editForm')
      // 事件委托的方式给tbody绑定
      tbody.addEventListener('click', function(e){
        if (e.target.classList.contains('btn-update')){

          axios({
            url:`/api/books/${e.target.dataset.id}`,
          }).then(({data:res}) => {
            // 填充内容
            for(let key in res.data){
              editForm.querySelector(`[name=${key}]`).value = res.data[key]
            }

          })
          editModel.show()

        } // 处理编辑的逻辑
      })

      // 保存 
      const editBtn = document.querySelector('#editBtn')
      editBtn.addEventListener('click', function(){
        // 获取表单元素的数据，发给后端
        const data = serialize(editForm, {hash:true})
        console.log(data)
        axios({
            url:`/api/books/${data.id}`,
            method:'put',
            data, // 别忘了参数data
        }).then(res => {
            console.log(res)
            // 提示更新修改成功
            alert(res.data.message)
            // 关闭弹窗
            editModel.hide()
            // 更新数据
            getBooks()
        })
      })

    </script>
  </body>
</html>
